package com.wang.lock;

import java.util.LinkedList;

public class WaitThread{

    public static void main(String[] args) {
        FruitStore fruitStore = new FruitStore();
        Consumer c = new Consumer(fruitStore);
        Thread thread_c = new Thread(c);
        c.setNum(80);
        thread_c.start();
        Producer p = new Producer(fruitStore);
        Thread thread_p = new Thread(p);
        p.setNum(90);
        thread_p.start();
    }

}

class FruitStore {
    private final int MAX_SIZE = 100;
    private LinkedList list = new LinkedList();

    public void consumer(int num){
        synchronized (list){
            while (num > list.size()){
                System.out.println("打算消费："+num);
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for (int i = 0;i<num;i++){
                list.remove();
            }
            System.out.println("消费："+num);
            list.notify();
        }
    }

    public void producer(int num){
        synchronized (list){
            while (list.size()+num > MAX_SIZE){
                System.out.println("要生产："+num);
                try{
                    list.wait();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            for(int i = 0;i<num;i++){
                list.add(new Object());
            }
            System.out.println("生产"+num);
            list.notifyAll();
        }
    }
}

class Producer implements Runnable{
    private int num;
    public FruitStore fruitStore;

    public Producer(FruitStore fruitStore){
        this.fruitStore = fruitStore;
    }

    public void setNum(int num) {
        this.num = num;
    }

    @Override
    public void run() {
        fruitStore.producer(num);
    }
}

class Consumer implements Runnable{
    private int num;
    public FruitStore fruitStore;

    public Consumer(FruitStore fruitStore){
        this.fruitStore = fruitStore;
    }

    public void setNum(int num) {
        this.num = num;
    }

    @Override
    public void run() {
        fruitStore.consumer(num);
    }
}